package jike.demo37;

import jike.demo35.IdGenerator;
import org.apache.log4j.Logger;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: TODO
 * @date 2023/4/26 22:03
 */
public class RandomIdGenerator implements IdGenerator {
    private static final Logger logger = Logger.getLogger(RandomIdGenerator.class);

    @Override
    public String generate() throws IdGenerationFailureException {

        String substrOfHostName = null;
        try {
            substrOfHostName = getLastfieldOfHostName();
        } catch (UnknownHostException e) {
            throw new IdGenerationFailureException("host name is empty !");
        }
        long currentTimeMillis = System.currentTimeMillis();
        String randomString = generateRandomAlphameric(8);
        String id = String.format("%s-%d-%s",
                substrOfHostName, currentTimeMillis, randomString);

        return id;
    }

    /**
     * @description: 生成8位随机数
     * @author oyz
     * @param length
     * @date 2023/4/24 21:52
     * @version 1.0
     */
    private String generateRandomAlphameric(int length) {
        char[] randomChars = new char[length];
        int count = 0;
        Random random = new Random();
        while (count < length) {
            int randomAscii = random.nextInt(122);
            if (randomAscii >= 48 && randomAscii <= 57) {
                randomChars[count] = (char)('0' + (randomAscii - 48));
                count++;
            } else if (randomAscii >= 65 && randomAscii <= 90) {
                randomChars[count] = (char)('A' + (randomAscii - 65));
                count++;
            } else if (randomAscii >= 97 && randomAscii <= 122) {
                randomChars[count] = (char)('a' + (randomAscii - 97));
                count++;
            }
        }
        return new String(randomChars);
    }

    /**
     * 生成主机地址
     * @return String
     */
    private String getLastfieldOfHostName() throws UnknownHostException {
        String hostName = InetAddress.getLocalHost().getHostName();
        if(hostName == null || hostName.isEmpty()){
            throw new UnknownHostException("dont know this host name !");
        }

        return getLastSubstrSplittedByDot(hostName);
    }

    private String getLastSubstrSplittedByDot(String hostName) {
        String[] tokens = hostName.split("\\.");
        if (tokens.length > 0) {
            hostName = tokens[tokens.length - 1];
        }
        return hostName;
    }
}
